package com.piece.core.framework.support.dto;

import com.piece.core.framework.constant.*;
import com.piece.core.framework.util.collection.ArrayUtil;
import com.piece.core.framework.util.object.ObjectUtil;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.*;

/**
 * 登录用户信息
 */
@Getter
@Setter
public class UserDetailDTO extends User {

    private String id;       //用户ID
    private String loginName;//用户名字
    private String deptId;   //部门ID
    private String deptName; //部门名称
    private String salt;     //盐值
    private String openID;   //OPENID
    private String avatar;   //用户头像
    private Object detail;   //用户详细信息

    public UserDetailDTO(String loginName) {
        super(loginName, null, null);
        this.loginName = loginName;
    }

    public UserDetailDTO(String id, String loginName, String username, String password, String salt, String deptId, String deptName, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.id = id;
        this.salt = salt;
        this.loginName = loginName;
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public UserDetailDTO(String loginName, String username, String password, String salt, String deptId, String deptName, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.salt = salt;
        this.loginName = loginName;
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public UserDetailDTO(String loginName, String password, String openId) {
        super(loginName, password, null);
        this.loginName = loginName;
        this.openID = openId;
    }

    public boolean isAdmin() {
        return isPermitted(PermissionConstants.ADMIN_PERMISSION);
    }

    public boolean isPermitted(String permission) {
        List<String> permissionKeys = permissions();
        if (ObjectUtil.isEmpty(permissionKeys)) {
            return false;
        }

        if (permissionKeys.contains(PermissionConstants.ADMIN_PERMISSION)) {
            return true;
        }

        String[] perms = permission.split(FrameWorkConstants.SPLIT_PARAM);
        for (int i = 0; i < perms.length; i++) {
            if (permissionKeys.contains(permission)) {
                return true;
            }
        }
        return false;
    }

    public String[] permission() {
        return ArrayUtil.convertArray(permissions());
    }

    private List<String> permissions() {
        Collection<GrantedAuthority> authorities = getAuthorities();
        if (null == authorities) {
            return null;
        }

        List<String> permissionKeys = new ArrayList<>();
        authorities.stream().forEach(authority -> {
            permissionKeys.add(authority.getAuthority());
        });

        return permissionKeys;
    }
}